package com.leyou.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.entity.Brand;
import com.leyou.mapper.BrandMapper;
import com.leyou.service.BrandService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Slf4j
@Service
public class BrandServiceImpl implements BrandService{

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public PageInfo<Brand> selectBrandPageInfo(Integer pageNum, Integer pageSize, String sortColumn, boolean isDesc, String key) throws Exception {
        // 开始分页
        PageHelper.startPage(pageNum, pageSize);
        // 条件过滤
        Example example = new Example(Brand.class);
        if (StringUtils.isNotBlank(key)) {
            example.createCriteria().andLike("name", "%" + key + "%")
                    .orEqualTo("letter", key);
        }
        if (StringUtils.isNotBlank(sortColumn)) {
            // 排序
            String str = sortColumn + (isDesc ? " desc" : " asc");
            log.info("orderBy:" + str);
            example.setOrderByClause(str);
        }
        // 查询
        Page<Brand> page = (Page<Brand>) brandMapper.selectByExample(example);
        PageInfo<Brand> pageInfo = page.toPageInfo();
        return pageInfo;
    }

    @Override
    public void saveBrand(Brand brand, List<Long> cids) {
        // 新增品牌信息
        brandMapper.insertSelective(brand);
        log.info(brand.toString());
        // 新增品牌和分类中间表
        cids.forEach(cid -> brandMapper.saveCategoryBrand(cid,brand.getId()));
    }
}
